//
//  PersonalRegStep1ViewController.m
//  CarTown
//
//  Created by 熊浩 on 15/7/31.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "PersonalRegStep1ViewController.h"
#import "Utils.h"
#import "PersonalRegStep2ViewController.h"
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "ValidateCode.h"
#import "UpdatePersonalPassViewController.h"
#import "ResMode.h"
#import "Puser.h"
#import "UserLoignInfo.h"
#import "UserInfoUpdateResde.h"
#import "MyInfoTableViewController.h"
@interface PersonalRegStep1ViewController (){
    int count;
    NSString *phone;
}
@property (weak, nonatomic) IBOutlet UIButton *getvalidatecode_btn;
@property (weak, nonatomic) IBOutlet UIButton *next_step_btn;
@property (weak, nonatomic) IBOutlet UIView *backview;
@property (weak, nonatomic) IBOutlet UITextField *validatecode;
@property (nonatomic,weak) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UITextField *phonenumber;
@property (nonatomic,strong) ValidateCode *code;
@property (nonatomic,strong) UserLoignInfo *usermode;
@end

@implementation PersonalRegStep1ViewController

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.backview.layer.borderWidth=1;
    self.backview.layer.borderColor=[UIColorFromRGB(0xe5e5e5) CGColor];
    self.next_step_btn.layer.cornerRadius=5;
    self.navigationController.navigationBarHidden=NO;
    self.navigationItem.title=self.isreg?@"个人注册":@"找回密码";
    if (self.pass) {
        self.navigationItem.title=@"新手机号";
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    count=90;
}
- (IBAction)NexTclick:(id)sender {
    
    if([self checkvalitecode]){
        
        if(self.isreg){
            UIStoryboard *board=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            PersonalRegStep2ViewController *vc= [board instantiateViewControllerWithIdentifier:@"personal_step2"];
            vc.phone=self.phonenumber.text;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(self.pass)
        {
            [self updatephone];
        }
        else{
            UpdatePersonalPassViewController *vc=[UpdatePersonalPassViewController viewcontroller];
            vc.usermode=self.usermode;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}
-(void)updatephone{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    hud.labelText=@"正在修改..";
    hud.margin = 10.f;
    
    hud.removeFromSuperViewOnHide = YES;
    
    Puser *user=[Puser getUser];
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"user_id"]=user.user_id;
    params[@"action"]=@"p_phone_change";
    params[@"phone"]=self.phonenumber.text;
    params[@"passwd"]=self.pass;
    params[@"user_type"]=@"person";
    [PostUitls Post:userinfourl parameters:params success:^(id response) {
        hud.mode=MBProgressHUDModeText;
        UserInfoUpdateResde *resde=[UserInfoUpdateResde resdeWithDict:response];
        if ([resde.state intValue]==400) {
            user.user_mobile=self.phonenumber.text;
            hud.labelText=@"修改成功";
            for (UIViewController *vc in self.navigationController.viewControllers) {
                if ([vc isKindOfClass:[MyInfoTableViewController class]]) {
                    [self.navigationController popToViewController:vc animated:YES];
                }
            }
        }else{
            hud.labelText=@"修改失败";
            
        }
        [hud hide:YES afterDelay:1];
    } failure:^(NSError *error) {
        
    }];
}
-(BOOL)checkvalitecode{
    
    [self.validatecode endEditing:YES];
    [self.phonenumber endEditing:YES];
    if (self.phonenumber.text.length==0||self.phonenumber.text.length!=11) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"手机号码格式不正确";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    if(![self.phonenumber.text isEqualToString:phone]){
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"手机号码已被更改，请重新获取验证码";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
        
    }
    if (![self.validatecode.text isEqualToString:self.code.vericode]) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"验证码不正确";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        
        return false;
    }
    return true;
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.phonenumber endEditing:YES];
    [self.validatecode endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)getvalidatecode:(id)sender {
    
    if ([self checkfrom]) {
        
        if (self.isreg) {
            
            phone=self.phonenumber.text;
            [self getvalidatecodeFromWeb:YES];
        }else{
            [self getUserInfobyPhone];
        }
        
    }
    
    
    
}

-(void)getUserInfobyPhone{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"person";
    params[@"p_action"]=@"pselect";
    params[@"where"]=[NSString stringWithFormat:@"user_email=%@",self.phonenumber.text];
    [PostUitls Post:makepassurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        ResMode *resdmode=[ResMode modeWithDict:dict];
        if ([resdmode.state integerValue]==400) {
            NSArray *array=resdmode.data;
            UserLoignInfo *mode=[UserLoignInfo logininfoWithDict:array[0]];
            self.usermode=mode;
            [self StartTimer];
            phone=self.phonenumber.text;
            [self getvalidatecodeFromWeb:NO];
        }else{
            MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.labelText=@"没有该手机号";
            hud.mode = MBProgressHUDModeText;
            hud.margin = 10.f;
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
        }
        NSLog(@"%@",response);
    } failure:^(NSError *error) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        NSLog(@"%@",error);
    }];
}

-(void)getvalidatecodeFromWeb:(BOOL)isreg{
    
    if (isreg) {
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"action"]=@"check_per";
        params[@"username"]=self.phonenumber.text;
        [PostUitls Post:hosturl parameters:params success:^(id response) {
            
            NSDictionary *dict=response;
            NSNumber *data=dict[@"data"];
            if ([data integerValue]==2) {
                MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
                
                hud.labelText=@"该手机号已注册";
                hud.mode = MBProgressHUDModeText;
                
                hud.margin = 10.f;
                
                hud.removeFromSuperViewOnHide = YES;
                [hud hide:YES afterDelay:1];
            }else{
                [self StartTimer];
                AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
                manager.responseSerializer=[AFHTTPResponseSerializer serializer];
                NSMutableDictionary *params=[NSMutableDictionary dictionary];
                params[@"phone"]=self.phonenumber.text;
                
                [manager POST:smsvalidateurl parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
                    NSData *jsondata=responseObject;
                    
                    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:jsondata                                                         options:NSJSONReadingAllowFragments error:nil];
                    self.code=[ValidateCode codeWithDict:dict];
                    NSLog(@"%@",self.code);
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    NSLog(@"网络错误,请稍后重试");
                    NSLog(@"%@",error);
                }];
            }
            
        } failure:^(NSError *error) {
            MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            
            hud.labelText=@"网络错误";
            hud.mode = MBProgressHUDModeText;
            
            hud.margin = 10.f;
            
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
        }];
        
        
    }else{
        AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"phone"]=self.phonenumber.text;
        
        [manager POST:smsvalidateurl parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            NSData *jsondata=responseObject;
            
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:jsondata                                                         options:NSJSONReadingAllowFragments error:nil];
            self.code=[ValidateCode codeWithDict:dict];
            NSLog(@"%@",self.code);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"网络错误,请稍后重试");
            NSLog(@"%@",error);
        }];
        
    }
    
}
-(BOOL)checkfrom{
    
    
    [self.validatecode endEditing:YES];
    [self.phonenumber endEditing:YES];
    if (self.phonenumber.text.length==0||self.phonenumber.text.length!=11) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"请填写正确的手机号码";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    return true;
}
-(void)StartTimer{
    NSTimer *timer=[NSTimer timerWithTimeInterval:1 target:self selector:@selector(updatecouts) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    self.getvalidatecode_btn.enabled=NO;
    self.timer=timer;
}

-(void)endtimer{
    [self.timer invalidate];
}
-(void)dealloc{
    if (self.timer) {
        [self endtimer];
    }
}

-(void)updatecouts{
    if (count>0) {
        count--;
        self.getvalidatecode_btn.titleLabel.text=[NSString stringWithFormat:@"%d秒后重新获取",count];
        [self.getvalidatecode_btn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",count] forState:UIControlStateNormal];
        
    }else{
        self.getvalidatecode_btn.titleLabel.text=@"重新获取";
        self.getvalidatecode_btn.enabled=YES;
        [self.getvalidatecode_btn setTitle:@"重新获取" forState:UIControlStateNormal];
        [self endtimer];
        count=90;
        
    }
    
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
